<template>
  <!-- 师资列表 -->
  <div class="booking-list c-maxw640">
    <div class="c-w100 c-p c-hh270 c-pf c-bg-white c-maxw640 c-w100 c-p-l0 c-p-r0 c-m-0auto c-pz99" :class="unenableTopNav || $isWxApp() ? 'c-p-t0' : 'top1'">
      <div class="c-w100 c-h c-maxw640 c-p-l0 c-p-t0 theme-bg-gradient2 c-pa c-pz1"></div>
      <div class="c-justify-center c-flex-row c-aligni-center c-pv30 c-ph24 c-pz10 c-p">
        <div @click="chooseCity" class="c-flex-row c-aligni-center c-fc-white c-mr20 c-flex-grow1 c-w0">
          <i class="iconfont c-fs22 c-mr10">&#xe7f1;</i>
          <div class="c-flex-row c-aligni-center c-text-ellipsis1">
            <div class="c-fs28 c-text-ellipsis1">{{locateAddress}}</div>
            <i class="iconfont c-fs16 c-mt5">&#xe908;</i>
          </div>
        </div>
        <div class="c-fc-white c-br30 c-fs24 c-hh60 c-flex-row c-aligni-center c-ph16 booking-search" :class="longSearch ? 'c-ww400' : 'c-ww270'">
          <span class="iconfont c-fs26">&#xe6d6;</span>
          <form action="javascript:return true;" class="c-h c-lh60">
            <input ref="input" @focus="inputFocus" @blur="inputBlur(longSearch ? 1 : null)" class="c-w100 c-h c-lh60 c-fc-white" v-model="searchValue" :placeholder="longSearch ? '输入讲师名及标签搜索' : '输入关键字搜索'" type="text" @keyup.enter="startSearch(searchValue)">
          </form>
        </div>
      </div>
      <section class="c-flex-row c-pz99 c-fc-white c-aligni-center c-pb30 c-ph24 c-p">
        <div class="c-flex-row c-aligni-baseline c-w100 c-pz99">
          <div class="c-text-hidden c-flex-1">
            <div class="c-p" ref="nav">
              <div class="c-menu__list c-p c-flex-row c-aligni-center">
                <div @click="chooseAll" class="c-mr54 c-p c-flex-shrink0 c-fs26" :class="{'c-fs30 c-fw-b': activeTag == 0}">全部</div>
                <div
                  class="c-menu__item c-mr54 c-p c-flex-shrink0 c-fs26"
                  :class="{'c-fs30 c-fw-b': activeTag == index + 1}"
                  :key="index"
                  v-for="(item, index) in allTags"
                  @click="changeTab(item.alId,index)"
                >{{item.name}}
                </div>
              </div>
            </div>
          </div>
          <div
            class="iconfont c-fs28 c-fs24 c-ml26 c-mt5 c-pz99 close"
            :class="!isShow ? 'c-rotate180' : ''"
            @click="clickDown"
          >&#xe67a;</div>
        </div>
        <!-- 全部标签半弹窗 -->
        <transition name="fade-opacity50">
          <div class="mask c-m-0auto" :class="unenableTopNav || $isWxApp() ? 'c-p-t0' : 'top1'" @click="clickClose" v-show="isShow">
            <div class="c-pa c-pz100 c-w100 c-p-l0 c-p-r0 c-m-0auto c-br-bl20 c-br-br20 c-text-hidden">
              <transition name="fade-translatey">
                <div class="c-ph24 c-pt30 c-pb40 c-fs24 c-fc-sblack c-bg-white c-p c-pz100 c-w100 c-maxw640" v-show="isShow">
                  <div class="c-fs28 c-fw-b">标签类型</div>
                  <div class="c-text-hidden c-mh-12 ">
                    <div class="c-w33 fl" @click="chooseAll">
                      <div class="c-ww180 c-mt30 c-textAlign-c c-hh54 c-lh54 c-br25 c-mh12" :class="removeAll == true ? 'booking-tag' : 'theme-bg c-fc-white'">全部</div>
                    </div>
                    <div v-for="(item,index) in allTags" :key="item.alId" class="c-w33 fl">
                      <div :class="alId == item.alId ? 'theme-bg c-fc-white' : 'booking-tag'" class=" c-ww180 c-mt30 c-textAlign-c c-hh54 c-lh54 c-br25 c-mh12" @click="changeTab(item.alId,index)">{{item.name}}</div>
                    </div>
                  </div>
                </div>
              </transition>
            </div>
          </div>
        </transition>
      </section>
      <div class="c-flex-row c-fs28 c-hh100 c-lh100 c-bg-white c-br-tl20 c-br-tr20 c-pz10 c-p">
        <div @click="changeType(1)" class="c-w50 c-textAlign-c" :class="sortType == 1 ? 'c-fc-xblack c-fw-b' : 'c-fc-sblack'">综合</div>
        <div @click="changeType(2)" class="c-w50 c-textAlign-c" :class="sortType == 2 ? 'c-fc-xblack c-fw-b' : 'c-fc-sblack'">距离</div>
      </div>

    </div>
    <!-- 师资列表 -->
    <div class="c-p c-w100 mt200 c-pz98">
      <booking-com :bookingList='bookingList' :isList='isList' v-if="bookingList.length > 0"></booking-com>
      <loading-status-tem :showLoading="isLoading" :noMoreData="is_page == false && (bookingList && bookingList.length > 0 )" :noData="!isLoading && (!bookingList || bookingList.length == 0)" :noDataText="'暂无师资'"></loading-status-tem>
      <!-- 标签筛选框 -->
    </div>

    <!-- 我的预约 -->
    <div class="c-w100 c-maxw640 c-ph24 c-pf c-p-b0 c-p-l0 c-p-r0 c-m-0auto c-pz1000 c-pv18 c-bg-white">
      <div @click="goMyBooking" class="theme-bg c-w100 c-hh64 c-lh64 c-fc-white c-fs26 c-textAlign-c c-br32">我的预约</div>
    </div>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import { utilJs } from "@/utils/common.js"
import { loadBMap } from "@/utils/loadBMap.js"
import bookingCom from "@/components/templates/bookingCom.vue";
let inputScrollTop = 0;
export default {
  name: "BookingList",
  components: {
    loadingStatusTem,
    bookingCom,
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      themeName: localStorage.getItem("themeName") ? localStorage.getItem("themeName") : "mb5",
      isLoading: false,
      dataStatus: 'HAS_MORE_DATA',
      selectedTag: '',
      allTags: [],
      bookingList: [],
      alId: '',
      is_page: false,
      page: 1,
      limit: 10,
      removeAll: false,
      isShow: false,
      searchValue: '',
      isFocus: false,
      isList: true,
      activeTag: 0,
      locateCity: '未知',
      locateAddress: '未知',
      sortType: 1, //1综合排序 2距离排序
      longSearch: false, //是否显示长搜索框
      lat: '',
      lng: '',
      isIos: false,
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
    }
  },
  computed: {
    // 判断是否有顶部导航
    unenableTopNav() {
      return this.companyAuth && this.companyAuth.companyTopNav && this.companyAuth.companyTopNav.style && this.companyAuth.companyTopNav.style == 5
    },
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
  },
  activated() {
    this.isLoading = false;
    this.page = 1;
    this.is_page = false;
    this.searchValue = '';
    this.allTags = [];
    this.alId = "";
    this.activeTag = 0;
    this.bookingList = [];
    this.bookingName = "";
    this.selectedTag = "";
    this.removeAll = false;
    this.isShow = false;
    this.isFocus = false;
    this.isList = true;
    this.locateAddress = this.$route.query.detailPosition || '未知';
    this.locateCity = this.$route.query.locateCity || '未知';
    this.isiOS = navigator.userAgent.indexOf("IOSLogin") > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1;
    this.$nextTick(function () {
      loadBMap().then(BMap => {
        if (this.locateAddress == '未知') {
          this.getLocation();
        } else {
          this.getTags();
        }
      })
    })
    this.sortType = 1;
    this.longSearch = false;
    this.lat = this.$route.query.lat || '';
    this.lng = this.$route.query.lng || '';
    setDocumentTitle("师资列表");
    inputScrollTop = this.$route.query.inputScrollTop || 0;
    document.body.scrollTop = inputScrollTop - 1 || 0;
    window.addEventListener('scroll', this.windowScrollFunction);
    this.wechatShare();
  },
  watch: {
    activeTag(newIndex, oldIndex) {
      this.scrollTabMenu(newIndex);
    }
  },
  methods: {
    scrollTabMenu(newIndex) {
      let nav = this.$refs.nav;
      let item = nav.querySelectorAll(".c-menu__item");
      // 获取窗口的大小
      let cMenuList = nav.querySelector(".c-menu__list");
      let windowWidth = cMenuList.clientWidth / 2;
      if (newIndex !== 0) {
        let activeItemWidth = item[newIndex - 1].clientWidth;
        nav.scrollLeft = item[newIndex - 1].offsetLeft - (windowWidth - activeItemWidth / 2);
      }
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur(isLong) {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
      if (isLong == 1) {
        this.longSearch = false
      }
    },
    //更改排序选项
    changeType(type) {
      this.sortType = type;
      this.bookingList = [];
      this.page = 1;
      this.getTeacherList();
    },
    // 百度地图定位
    getLocation() {
      //安卓app需要弹窗申请权限
      if (utilJs.isAndroidApp()) {
        this.$cjConfirm({
          title: '位置权限申请', //
          message: '需要授权定位,用于获取当前位置附近的师资列表',
          onConfirm:() => {
           this.startGetLocation();
          },
          onCancel:() => {
            this.getTags();
          },
        })
        return;
      }
      this.startGetLocation();
    },
    startGetLocation() {
      /* eslint-disable */
      let that = this;
      that.$loading.hide();
      that.$loading.show({
        text: "定位中"
      });
      let geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          that.lng = r.point.lng;
          that.lat = r.point.lat;
          let gc = new BMap.Geocoder();
          gc.getLocation(r.point, function (rs) {
            const addComp = rs.addressComponents;
            // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
            that.locateCity = addComp.city;
            that.locateAddress = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
            that.getTags();
          })
        }
        else {
          that.getTags();
        }
      });
      /* eslint-disable */
    },
    // 高德定位
    // getLocation() {
    //   let that = this;
    //   that.$loading.show({
    //     text: "定位中"
    //   });
    //   /* eslint-disable */
    //   AMap.plugin('AMap.Geolocation', function() {
    //     var geolocation = new AMap.Geolocation({
    //       // 是否使用高精度定位，默认：true
    //       enableHighAccuracy: true,
    //       // 设置定位超时时间，默认：无穷大
    //       timeout: 10000,
    //     })

    //     geolocation.getCurrentPosition()
    //     AMap.event.addListener(geolocation, 'complete', onComplete)
    //     AMap.event.addListener(geolocation, 'error', onError)

    //     function onComplete (data) {
    //       that.$loading.hide();
    //       // data是具体的定位信息
    //       let locateAddress = data.addressComponent;
    //       that.getTags();
    //       that.locateAddress = locateAddress.city + locateAddress.district + locateAddress.township + locateAddress.street + locateAddress.streetNumber;
    //       that.locateCity = locateAddress.city;
    //       that.lng = data.position.split(',')[0];
    //       that.lat = data.position.split(',')[1];
    //     }

    //     function onError (data) {
    //       that.$loading.hide();
    //       // 定位出错
    //       that.getTags();
    //     }
    //   })
    //   /* eslint-disable */
    // },
    chooseCity() {
      this.$routerGo(this, "push", { path: `/homePage/booking/cityPicker?locateAddress=${this.locateAddress}&locateCity=${this.locateCity}` });
    },
    clickDown() {
      this.isShow = !this.isShow;
      if (this.isShow) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = 'auto';
      }
    },
    clickClose() {
      this.isShow = false;
      document.body.style.overflow = 'auto';
    },
    //   获取标签
    getTags() {
      let $this = this;
      utilJs.getMethod(`${global.apiurl}appointment/getLabelList?limit=20`, res => {
        $this.allTags = res.data;
        $this.getTeacherList();
      }, failRes => {
      });
    },
    //   获取列表
    getTeacherList() {
      let $this = this;
      if ($this.isLoading == true) {
        return;
      }
      $this.isLoading = true;
      utilJs.getMethod(`${global.apiurl}appointment?alId=${this.alId}&keyWord=${this.searchValue}&lat=${this.lat}&lng=${this.lng}&sortType=${this.sortType}&page=${this.page}&limit=${this.limit}`, res => {
        $this.$loading.hide();
        if ($this.page == 1) {
          $this.bookingList = res.data;
        } else {
          $this.bookingList = [...this.bookingList, ...res.data];
        }
        $this.page = res.data && (res.data.length >= $this.limit) ? ($this.page + 1) : $this.page;
        $this.is_page = res.data && (res.data.length >= $this.limit) ? true : false;
        $this.isLoading = false;
      }, failRes => {
        $this.$loading.hide();
        $this.isLoading = false;
      });
    },
    // 切换tab
    changeTab(alId, index) {
      this.bookingList = [];
      this.alId = alId;
      this.activeTag = index + 1;
      this.page = 1;
      this.removeAll = true;
      this.getTeacherList();
      this.isShow = false;
      document.body.style.overflow = 'auto';
    },
    chooseAll() {
      this.alId = '';
      this.activeTag = 0;
      this.bookingList = [];
      this.page = 1;
      this.removeAll = false;
      this.getTeacherList();
      this.isShow = false;
      this.scrollTabMenu(1)
      window.scrollTo(0, 0);
      document.body.style.overflow = 'auto';
    },
    goMyBooking() {
      this.$routerGo(this, "push", {
        path: '/member/myBooking/myBookingList'
      })
    },
    //分享
    wechatShare: function () {
      let title = "师资列表";
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      utilJs.wechatConfig(shareUrl, title, "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let title = "师资列表";
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      utilJs.appShareTrue(title, "", shareUrl, "");
    },
    windowScrollFunction: function () {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.is_page == true) {
          that.getTeacherList();
        }
      });
    },
    startSearch(e) {
      this.page = 1;
      this.bookingList = [];
      this.searchValue = e;
      this.getTeacherList();
    },
  },
  deactivated() {
    this.is_page = false;
    this.$loading.hide();
    document.body.style.overflow = 'auto';
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
}
</script>

<style scoped>
.booking-list {
  background-size: 100% 130px;
}
input {
  font-size: 0.65rem;
  padding: 0 0 0 0.4rem;
  border: 0;
  background: none;
  outline: none;
}

input:focus {
  outline: none;
}
input[type="search"] {
  -webkit-appearance: textfield;
  -webkit-box-sizing: content-box;
}
input::-webkit-search-decoration,
input::-webkit-search-cancel-button {
  display: none;
}
.booking-search {
  background: rgba(255, 255, 255, 0.3);
}
::-webkit-input-placeholder {
  /* WebKit browsers */
  color: rgba(255, 255, 255, 0.7);
}
:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: rgba(255, 255, 255, 0.7);
}
::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: rgba(255, 255, 255, 0.7);
}
:-ms-input-placeholder {
  /* Internet Explorer 10+ */
  color: rgba(255, 255, 255, 0.7);
}
.booking-tag {
  background-color: #f5f6f6;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100vh;
  z-index: 100;
}
.c-pz96 {
  z-index: 96;
}
.c-pz97 {
  z-index: 97;
}
.c-lh54 {
  line-height: 1.35rem;
}
.c-mt30 {
  margin-top: 0.75rem;
}
.c-hh236 {
  height: 5.9rem;
}
.c-mh12 {
  margin-left: 0.3rem;
  margin-right: 0.3rem;
}
.c-mh-12 {
  margin-left: -0.3rem;
  margin-right: -0.3rem;
}
.c-hh268 {
  height: 6.7rem;
}
/* 导航栏样式 */
.close {
  transition-duration: 0.5s;
  transition-timing-function: ease;
}
.myBooking {
  box-shadow: 0 2px 4px 0 rgba(254,121,0,0.30);
  border-radius: 2.5rem 0 0 2.5rem;
}
.mt200 {
  margin-top: 7rem;
}
.top1 {
  top: 1.7rem;
}
/* 弹窗从上往下动画 */
/* 弹窗从下往上动画 */
.fade-translatey-enter-active{
  animation: showTranslatey 0.6s forwards;
}
.fade-translatey-leave-active{
  animation: hideTranslatey 0.6s forwards;
}
@keyframes showTranslatey {
  from {
    transform: translateY(-100%);
  }
  to {
    transform: translateY(0);
  }
}
@keyframes hideTranslatey {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-100%);
  }
}
/* 弹窗出现透明度动画 */
.fade-opacity50-enter-active{
  animation: showOpacity50 0.5s forwards;
}
.fade-opacity50-leave-active{
  animation: hideOpacity50 0.5s forwards;
}
@keyframes showOpacity50 {
  from {
    opacity: 0.5;
  }
  to {
    opacity: 1;
  }
}
@keyframes hideOpacity50 {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.5;
  }
}
</style>